import Message from 'tdesign-miniprogram/message/index';
import { novelAPI } from '~/api/novel';
const authUtils = require('~/utils/auth.js');

Page({
  data: {
    // 小说信息
    novelData: null,
    novelId: '',
    
    // 章节数据
    chapterData: {
      title: '',
      content: ''
    },
    
    // 下一章节号
    nextChapterNumber: 1,
    
    // 写作进度
    writingProgress: 0,
    
    // 协作相关
    countdown: '',
    showPreviousChapter: false,
    previousChapter: null,
    
    // 阅读时间
    readingTime: 0,
    
    // 状态
    publishing: false,
    canPublish: false,
    
    // 草稿自动保存
    autoSaveTimer: null,
    lastSaveTime: null
  },

  /**
   * 页面加载
   */
  onLoad(options) {
    const { novelId } = options;
    if (!novelId) {
      Message.error({
        context: this,
        content: '小说ID不能为空'
      });
      wx.navigateBack();
      return;
    }

    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    this.setData({ novelId });
    this.loadNovelData();
    this.startAutoSave();
    
    // 协作模式特殊功能
    if (this.data.novelData && this.data.novelData.creationType === 2) {
      this.loadPreviousChapter();
      this.startCountdown();
    }
  },

  /**
   * 页面卸载
   */
  onUnload() {
    this.stopAutoSave();
    
    // 清除倒计时定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },

  /**
   * 返回上一页
   */
  onBack() {
    if (this.hasUnsavedChanges()) {
      wx.showModal({
        title: '提示',
        content: '有未保存的内容，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    } else {
      wx.navigateBack();
    }
  },

  /**
   * 加载小说数据
   */
  async loadNovelData() {
    try {
      const [novelResponse, chaptersResponse] = await Promise.all([
        novelAPI.getNovelDetail(this.data.novelId),
        novelAPI.getNovelChapters(this.data.novelId)
      ]);

      if (novelResponse.code === 200) {
        const novelData = novelResponse.data;
        this.setData({ novelData });

        // 检查写作权限
        if (!novelData.isParticipant) {
          Message.error({
            context: this,
            content: '您不是该小说的参与者'
          });
          wx.navigateBack();
          return;
        }

        if (novelData.status !== 2) {
          Message.error({
            context: this,
            content: '该小说不在进行中状态'
          });
          wx.navigateBack();
          return;
        }
      }

      if (chaptersResponse.code === 200) {
        const chapters = chaptersResponse.data || [];
        this.setData({ 
          nextChapterNumber: chapters.length + 1 
        });
      }

      // 先重置章节数据，然后尝试恢复草稿
      this.resetChapterData();
      this.loadDraft();
      
      
    } catch (error) {
      console.error('加载小说数据失败:', error);
      Message.error({
        context: this,
        content: '加载数据失败，请重试'
      });
      wx.navigateBack();
    }
  },

  /**
   * 章节标题输入
   */
  onChapterTitleInput(e) {
    this.setData({
      'chapterData.title': e.detail.value
    });
    this.updateWritingProgress();
    this.calculateReadingTime();
    this.checkPublishPermission();
    
    // 智能滚动，保持输入区域在统计栏上方可见
    this.scrollToKeepInputVisible();
  },

  /**
   * 内容输入
   */
  onContentInput(e) {
    this.setData({
      'chapterData.content': e.detail.value
    });
    this.updateWritingProgress();
    this.calculateReadingTime();
    this.checkPublishPermission();
    
    // 自动保存草稿
    this.startAutoSave();
    
    // 智能滚动，保持输入区域在统计栏上方可见
    this.scrollToKeepInputVisible();
  },

  /**
   * 更新写作进度
   */
  updateWritingProgress() {
    const { chapterData } = this.data;
    const titleProgress = Math.min((chapterData.title.trim().length / 10) * 30, 30);
    const contentProgress = Math.min((chapterData.content.trim().length / 1000) * 70, 70);
    const totalProgress = Math.round(titleProgress + contentProgress);
    
    this.setData({
      writingProgress: totalProgress
    });
  },

  /**
   * 计算预计阅读时间
   */
  calculateReadingTime() {
    const { chapterData } = this.data;
    const contentLength = chapterData.content.trim().length;
    
    if (contentLength === 0) {
      this.setData({ readingTime: 0 });
      return;
    }
    
    // 更现实的阅读速度计算：
    // 中文阅读速度：每分钟200-300字（取250字/分钟）
    // 考虑思考时间，实际阅读速度会更慢一些
    const wordsPerMinute = 250;
    const readingMinutes = Math.max(1, Math.round(contentLength / wordsPerMinute));
    
    this.setData({ readingTime: readingMinutes });
  },

  /**
   * 智能滚动，保持输入区域在统计栏上方可见
   */
  scrollToKeepInputVisible() {
    // 延迟执行，等待DOM更新
    setTimeout(() => {
      try {
        const query = wx.createSelectorQuery().in(this);
        
        // 获取页面滚动信息
        query.selectViewport().scrollOffset();
        
        // 获取textarea的位置信息
        query.select('.main-editor').boundingClientRect();
        
        query.exec((res) => {
          if (res[0] && res[1]) {
            const scrollOffset = res[0];
            const editorRect = res[1];
            
            // 获取屏幕高度和底部栏高度（大约160rpx = 80px）
            const screenHeight = wx.getSystemInfoSync().windowHeight;
            const bottomBarHeight = 80; // 底部栏高度（像素）
            
            // 计算textarea底部位置
            const editorBottom = editorRect.top + editorRect.height;
            
            // 如果textarea底部接近或超过底部栏上方区域，需要滚动
            const safeZone = screenHeight - bottomBarHeight - 50; // 留50px缓冲区域
            
            if (editorBottom > safeZone) {
              // 计算需要滚动的距离
              const scrollDistance = editorBottom - safeZone + scrollOffset.scrollTop;
              
              // 平滑滚动到合适位置
              wx.pageScrollTo({
                scrollTop: scrollDistance,
                duration: 200
              });
            }
          }
        });
      } catch (error) {
        console.log('智能滚动失败:', error);
      }
    }, 100);
  },

  /**
   * 编辑小说标题
   */
  onEditTitle() {
    wx.showModal({
      title: '编辑小说标题',
      editable: true,
      placeholderText: '请输入小说标题',
      success: (res) => {
        if (res.confirm && res.content) {
          this.setData({
            'novelData.title': res.content
          });
        }
      }
    });
  },

  /**
   * 切换上一章回顾显示
   */
  togglePreviousChapter() {
    this.setData({
      showPreviousChapter: !this.data.showPreviousChapter
    });
  },

  /**
   * 加载上一章内容（协作模式）
   */
  async loadPreviousChapter() {
    if (this.data.novelData.creationType !== 2) return;
    
    try {
      const response = await novelAPI.getNovelChapters(this.data.novelId);
      if (response.code === 200 && response.data.length > 0) {
        // 获取最新的章节作为上一章
        const previousChapter = response.data[response.data.length - 1];
        this.setData({
          previousChapter: previousChapter
        });
      }
    } catch (error) {
      console.error('加载上一章失败:', error);
    }
  },

  /**
   * 启动倒计时（协作模式）
   */
  startCountdown() {
    if (this.data.novelData.creationType !== 2) return;
    
    // 模拟24小时倒计时
    const endTime = Date.now() + 24 * 60 * 60 * 1000;
    
    const updateCountdown = () => {
      const now = Date.now();
      const remaining = endTime - now;
      
      if (remaining <= 0) {
        this.setData({ countdown: '时间已到' });
        return;
      }
      
      const hours = Math.floor(remaining / (1000 * 60 * 60));
      const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60));
      
      this.setData({
        countdown: `${hours}h ${minutes}m`
      });
    };
    
    updateCountdown();
    const timer = setInterval(updateCountdown, 60000); // 每分钟更新一次
    
    // 页面卸载时清除定时器
    this.countdownTimer = timer;
  },

  /**
   * 检查发布权限
   */
  checkPublishPermission() {
    const { chapterData } = this.data;
    const canPublish = chapterData.title.trim().length > 0 && 
                      chapterData.content.trim().length > 0;
    this.setData({ canPublish });
  },


  /**
   * 发布章节
   */
  async onPublishChapter() {
    console.log('开始发布章节...');
    const { chapterData, novelId } = this.data;
    
    // 防止重复提交
    if (this.data.publishing) {
      console.log('正在发布中，忽略重复请求');
      return;
    }
    
    // 表单验证
    if (!chapterData.title.trim()) {
      Message.warning({
        context: this,
        content: '请输入章节标题'
      });
      return;
    }

    if (!chapterData.content.trim()) {
      Message.warning({
        context: this,
        content: '请输入章节内容'
      });
      return;
    }

    if (chapterData.content.trim().length < 50) {
      Message.warning({
        context: this,
        content: '章节内容至少需要50字'
      });
      return;
    }

    try {
      console.log('设置发布状态为true');
      this.setData({ publishing: true });

      const publishData = {
        novelId: novelId,
        title: chapterData.title.trim(),
        content: chapterData.content.trim()
      };

      console.log('发布数据:', publishData);
      console.log('调用API发布章节...');
      const response = await novelAPI.writeChapter(publishData);
      console.log('API响应:', response);
      
      if (response.code === 200) {
        Message.success({
          context: this,
          content: '章节发布成功！'
        });

        // 清除草稿，但不清空内容（保持用户体验）
        this.clearDraft();

        // 延迟跳转回小说详情页，确保用户看到成功提示
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/novel-detail/index?novelId=${novelId}`,
            success: () => {
              console.log('跳转到小说详情页成功');
            },
            fail: (error) => {
              console.error('跳转到小说详情页失败:', error);
              // 如果跳转失败，尝试使用navigateTo
              wx.navigateTo({
                url: `/pages/novel-detail/index?novelId=${novelId}`
              });
            }
          });
        }, 1000);
      } else {
        console.error('发布失败，响应码不是200:', response);
        Message.error({
          context: this,
          content: response.message || '发布失败，请重试'
        });
      }
    } catch (error) {
      console.error('发布章节失败:', error);
      Message.error({
        context: this,
        content: error.message || '发布失败，请重试'
      });
    } finally {
      console.log('设置发布状态为false');
      this.setData({ publishing: false });
    }
  },


  /**
   * 保存草稿
   */
  onSaveDraft() {
    this.saveDraft();
    Message.success({
      context: this,
      content: '草稿已保存',
      duration: 1000
    });
  },

  /**
   * 开始自动保存
   */
  startAutoSave() {
    const timer = setInterval(() => {
      if (this.hasUnsavedChanges()) {
        this.saveDraft();
      }
    }, 30000); // 30秒自动保存一次

    this.setData({ autoSaveTimer: timer });
  },

  /**
   * 停止自动保存
   */
  stopAutoSave() {
    const { autoSaveTimer } = this.data;
    if (autoSaveTimer) {
      clearInterval(autoSaveTimer);
      this.setData({ autoSaveTimer: null });
    }
  },

  /**
   * 保存草稿到本地
   */
  saveDraft() {
    const { novelId, chapterData } = this.data;
    const draftKey = `chapter_draft_${novelId}`;
    
    wx.setStorageSync(draftKey, {
      ...chapterData,
      saveTime: new Date().getTime()
    });
    
    this.setData({ lastSaveTime: new Date().getTime() });
  },

  /**
   * 加载草稿
   */
  loadDraft() {
    const { novelId } = this.data;
    const draftKey = `chapter_draft_${novelId}`;
    
    try {
      const draft = wx.getStorageSync(draftKey);
      if (draft && draft.saveTime) {
        // 检查草稿是否在24小时内
        const now = new Date().getTime();
        const timeDiff = now - draft.saveTime;
        const hoursDiff = timeDiff / (1000 * 60 * 60);
        
        if (hoursDiff < 24) {
          this.setData({
            chapterData: {
              title: draft.title || '',
              content: draft.content || ''
            },
            lastSaveTime: draft.saveTime
          });
          
          this.checkPublishPermission();
          
          Message.info({
            context: this,
            content: '已恢复草稿内容',
            duration: 2000
          });
        } else {
          // 草稿过期，清除
          this.clearDraft();
        }
      }
    } catch (error) {
      console.error('加载草稿失败:', error);
    }
  },

  /**
   * 清除草稿
   */
  clearDraft() {
    const { novelId } = this.data;
    const draftKey = `chapter_draft_${novelId}`;
    
    try {
      wx.removeStorageSync(draftKey);
      this.setData({ lastSaveTime: null });
    } catch (error) {
      console.error('清除草稿失败:', error);
    }
  },

  /**
   * 重置章节数据
   */
  resetChapterData() {
    this.setData({
      chapterData: {
        title: '',
        content: ''
      },
      canPublish: false,
      writingProgress: 0,
      readingTime: 0
    });
  },

  /**
   * 检查是否有未保存的更改
   */
  hasUnsavedChanges() {
    const { chapterData, lastSaveTime } = this.data;
    
    // 如果有内容且没有保存过，或者内容有变化
    return (chapterData.title.length > 0 || chapterData.content.length > 0) && 
           (!lastSaveTime || new Date().getTime() - lastSaveTime > 60000); // 1分钟内的更改不算未保存
  }
});
